package com.vincent.seeyou;

import android.app.Application;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcEvent;
import android.preference.PreferenceManager;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.SDKInitializer;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.vincent.seeyou.ui.LoginActivity;
import com.vincent.seeyou.util.CollectionUtils;
import com.vincent.seeyou.util.SharePreferenceUtil;

import java.io.File;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import cn.bmob.im.BmobChat;
import cn.bmob.im.BmobUserManager;
import cn.bmob.im.bean.BmobChatUser;
import cn.bmob.im.db.BmobDB;
import cn.bmob.im.util.BmobLog;
import cn.bmob.v3.datatype.BmobGeoPoint;

/**
 * Created by vincent on 14-8-29.
 */

public class SYApplication extends Application {

    public static SYApplication syApplication;

    public static BmobGeoPoint lastPoint = null;
    public LocationClient locationClient;
    public SYLocationListener syLocationListener = new SYLocationListener();;

    public final String PREF_LATITUDE = "latitude";// 纬度
    public final String PREF_LONGTITUDE = "longtitude";// 经度

    private String latitude = "";
    private String longtitude = "";

    private MediaPlayer mediaPlayer;
    private NotificationManager notificationManager;
    private Map<String, BmobChatUser> contactList = new HashMap<String, BmobChatUser>();


    public static SYApplication getInstance() {
        return syApplication;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        //开启debug模式。
        BmobChat.DEBUG_MODE = true;
        syApplication = this;
        init();
    }



    private void init(){
        mediaPlayer = MediaPlayer.create(this, R.raw.notify);
        notificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);
        initImageLoader(getApplicationContext());
        // 若用户登陆过，则先从好友数据库中取出好友list存入内存中
        if (BmobUserManager.getInstance(getApplicationContext())
                .getCurrentUser() != null) {
            // 获取本地好友user list到内存,方便以后获取好友list
            contactList = CollectionUtils.list2map(BmobDB.create(
                    getApplicationContext()).getContactList());
        }
        initBaiduMap();
    }

    /** 初始化ImageLoader */
    public static void initImageLoader(Context context) {
        File cacheDir = StorageUtils.getOwnCacheDirectory(context,"bmobim/Cache");// 获取到缓存的目录地址

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                context).threadPoolSize(3).threadPriority(Thread.NORM_PRIORITY - 2) // 线程池内加载的数量
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new WeakMemoryCache())
                .discCacheFileNameGenerator(new Md5FileNameGenerator())             // 将保存的时候的URI名称用MD5 加密
                .discCache(new UnlimitedDiscCache(cacheDir))                        // 自定义缓存路径
                .tasksProcessingOrder(QueueProcessingType.LIFO).build();
        ImageLoader.getInstance().init(config);                                     // 全局初始化此配置
    }

    private void initBaiduMap(){

        // 初始化地图Sdk
        SDKInitializer.initialize(this);
        // 初始化定位sdk
        locationClient = new LocationClient(this.getApplicationContext());
        locationClient.registerLocationListener(syLocationListener);

    }

    public class SYLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {

            double latitude = location.getLatitude();
            double longtitude = location.getLongitude();
            if (lastPoint != null) {
                if (lastPoint.getLatitude() == location.getLatitude()
                        && lastPoint.getLongitude() == location.getLongitude()) {
                    BmobLog.i("两次获取坐标相同");// 若两次请求获取到的地理位置坐标是相同的，则不再定位

                    locationClient.stop();
                    return;
                }
            }
            lastPoint = new BmobGeoPoint(longtitude, latitude);
        }
    }

    public NotificationManager getNotificationManager() {
        if (notificationManager == null)
            notificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);
        return notificationManager;
    }

    public synchronized MediaPlayer getMediaPlayer() {
        if (mediaPlayer == null)
            mediaPlayer = MediaPlayer.create(this, R.raw.notify);
        return mediaPlayer;
    }


    public Map<String, BmobChatUser> getContactList() {
        return contactList;
    }

    public void setContactList(Map<String, BmobChatUser> contactList) {
        if (this.contactList != null) {
            this.contactList.clear();
        }
        this.contactList = contactList;
    }


    public String getLatitude() {
        SharedPreferences preferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        latitude = preferences.getString(PREF_LATITUDE, "");
        return latitude;
    }


    public void setLatitude(String lat) {
        SharedPreferences preferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = preferences.edit();
        if (editor.putString(PREF_LATITUDE, lat).commit()) {
            latitude = lat;
        }
    }

    public String getLongtitude() {
        SharedPreferences preferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        longtitude = preferences.getString(PREF_LONGTITUDE, "");
        return longtitude;
    }

    public void setLongtitude(String lon) {
        SharedPreferences preferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = preferences.edit();
        if (editor.putString(PREF_LONGTITUDE, lon).commit()) {
            longtitude = lon;
        }
    }

    // 单例模式，才能及时返回数据
    SharePreferenceUtil mSpUtil;
    public static final String PREFERENCE_NAME = "_sharedinfo";

    public synchronized SharePreferenceUtil getSpUtil() {
        if (mSpUtil == null) {
            String currentId = BmobUserManager.getInstance(
                    getApplicationContext()).getCurrentUserObjectId();
            String sharedName = currentId + PREFERENCE_NAME;
            mSpUtil = new SharePreferenceUtil(this, sharedName);
        }
        return mSpUtil;
    }

    /**
     * 退出登录,清空缓存数据
     */
    public void logout() {
        BmobUserManager.getInstance(getApplicationContext()).logout();
        setContactList(null);
        setLatitude(null);
        setLongtitude(null);
    }
}
